package com.swak.frame.ratelimit.spring.configuration;

import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import com.swak.frame.SwakConstants;
import com.swak.frame.ratelimit.annotation.EnableRateLimiting;
import com.swak.frame.ratelimit.annotation.RateLimitProperties;
import com.swak.frame.system.SwakAbstractConfiguration;

public abstract class AbstractRateLimitConfiguration extends SwakAbstractConfiguration implements ImportAware {

	protected RateLimitProperties rateLimitPropertie;

	@Override
	public void setImportMetadata(AnnotationMetadata importMetadata) {
		AnnotationAttributes enableRateLimiting = AnnotationAttributes
				.fromMap(importMetadata.getAnnotationAttributes(EnableRateLimiting.class.getName()));
		if (enableRateLimiting != null) {
			RateLimitProperties rateLimitConfig = new RateLimitProperties();
			rateLimitConfig.setDynamic(enableRateLimiting.getBoolean("dynamic"));
			rateLimitConfig.setType(enableRateLimiting.getEnum("limitType"));
			rateLimitConfig.setOrder(enableRateLimiting.getNumber("order"));
			this.rateLimitPropertie = rateLimitConfig;
		}
		if (enableRateLimiting == null) {
			this.rateLimitPropertie = Binder.get(systemConfig.getEnvironment())
					.bind(SwakConstants.SWAK_RATE_LIMIT, RateLimitProperties.class).get();
			if (this.rateLimitPropertie.getType() == null) {
				throw new IllegalArgumentException(
						"@EnableRateLimiting is not present on importing class " + importMetadata.getClassName());
			}
		}
	}
}
